//
//  ApplicationModel.m
//  WSPluginSwitcher
//
//  @author	Jens Krause [www.websector.de]
//	@date		01/01/09
//  @see		http://www.websector.de/blog/
//
//  Licensed under the MIT License http://www.opensource.org/licenses/mit-license.php
//


#import "ApplicationModel.h"
#import "Folder.h"
#import "Constants.h"


@implementation ApplicationModel

@synthesize archiveFlashPluginFolders; 
@synthesize selectedArchiveFlashPluginFolder;

#pragma mark --
#pragma mark init && dealoc

-(id)init{
	if (self = [super init]) {	
		
		archiveFlashPluginFolders = [[NSMutableArray alloc] init];
	
	}
	return self;
}

-(void)dealloc {
	
	[archiveFlashPluginFolders release];
	archiveFlashPluginFolders = nil;
	
	[selectedArchiveFlashPluginFolder release];
	selectedArchiveFlashPluginFolder = nil;
	
	[super dealloc];
	
	
}




/*
 * Helper method to generate a valid String for archive-folders
 *
 */
-(NSString *) getValidArchiveFlashPluginFolder:(NSString *)subFolderName{
	
	NSString *archiveFlashPluginsFolders = [[NSUserDefaults standardUserDefaults] stringForKey: KEY_ARCHIVE_FLASH_PLUGINS_FOLDERS ];
	NSString *validFolder = [archiveFlashPluginsFolders stringByAppendingString:subFolderName];
	validFolder = [validFolder stringByAppendingString:@"/"];
	
	return validFolder;
}

-(void)updateArchiveFlashPluginFolders
{
	
	NSString *archiveFlashPluginsFolders = [[NSUserDefaults standardUserDefaults] stringForKey: KEY_ARCHIVE_FLASH_PLUGINS_FOLDERS ];
	
	if (archiveFlashPluginsFolders != nil){
		
		NSFileManager *fileManager = [NSFileManager defaultManager];
		NSDirectoryEnumerator *direnum = [fileManager enumeratorAtPath: archiveFlashPluginsFolders];
		
		NSMutableArray *newArchiveFolders = [[NSMutableArray alloc] init];
		
		NSString *folderName;
		NSFileWrapper *fileWrapper;
		Folder *folder;
	
		while (folderName = [direnum nextObject]){
			
			// skip recursion
			[direnum skipDescendents];
			
			//
			// check hidden files
			BOOL isHiddenFile = [folderName hasPrefix:@"."];
			// 
			// and ignore hidden files
			if (!isHiddenFile) {
				//
				// check wheter folderName is a directory or not
				NSString *flashPluginFolderPath = [self getValidArchiveFlashPluginFolder:folderName];
				fileWrapper = [[NSFileWrapper alloc] initWithPath: flashPluginFolderPath];
				//
				// only directories should counted
				if ([fileWrapper isDirectory])
				{
					folder = [[Folder alloc] init];
					[folder setName: folderName];
					[folder setPath: flashPluginFolderPath];	
					
					// NSLog(@"folder %@", flashPluginFolderPath);
					
					[newArchiveFolders  addObject: folder ];
				}			
			}
			

			
			
		}
		//
		// store archive folders
		[self setArchiveFlashPluginFolders: [newArchiveFolders copy]];
		
		//
		// release 
		[folder, 
		 fileWrapper, 
		 fileManager, 
		 direnum, 
		 folderName,
		 newArchiveFolders
		 release];
		
	}
	
}





	
@end
